package com.hrms.config.security;

import com.hrms.config.security.detailservice.CustomerUserDetailService;
import com.hrms.config.security.filter.CheckTokenFilter;
import com.hrms.config.security.handler.CustomAccessDeinedHandler;
import com.hrms.config.security.handler.LoginFailureHandler;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Title: SpringSecurityConfig
 * @Author zhanji
 * @Package com.hrms.config.security
 * @description: SpringSecurity配置类
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SpringSecurityConfig{

    @Resource
    private CustomerUserDetailService customerUserDetailService;

    @Resource
    private LoginFailureHandler loginFailureHandler;

    @Resource
    private CustomAccessDeinedHandler customAccessDeinedHandler;

    @Resource
    private CheckTokenFilter checkTokenFilter;

    //配置我们自定的userDetailsService
    @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customerUserDetailService);
    }

    //密码加密
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //配置token过滤器
        http.addFilterBefore(checkTokenFilter , UsernamePasswordAuthenticationFilter.class)
            //解决跨域
            .csrf(AbstractHttpConfigurer::disable)
            .cors(AbstractHttpConfigurer::disable)
            .headers((headers)->headers.frameOptions((HeadersConfigurer.FrameOptionsConfig::disable)))
            //无状态
            .sessionManagement(session ->session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            //鉴权白名单，配置绕过鉴权的接口
            .authorizeHttpRequests((authorized)->authorized
                //过滤一些不需要token的接口地址
                .requestMatchers("/api/user/getImage","api/user/login","/api/uploadImage","/images/**").permitAll()
                .anyRequest().authenticated()
            )
            //指定登录鉴权时，查询用户的实现类
            .userDetailsService(customerUserDetailService)
            //自定义异常处理
            .exceptionHandling((exceptionHandling)->exceptionHandling
                .authenticationEntryPoint(loginFailureHandler)
                .accessDeniedHandler(customAccessDeinedHandler)
            );
        return http.build();
    }

    //注入AuthenticationManager
    @Bean
    public AuthenticationManager authenticationManagerBean(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }
}
